package com.shcd.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shcd.entity.ResultSelectMsg;
import com.shcd.mapperImpl.DataMonitoringMapperImpl;
import net.sf.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DataMonitoringService {
    private final DataMonitoringMapperImpl dataMonitoringMapperImpl;

    @Autowired
    public DataMonitoringService(DataMonitoringMapperImpl dataMonitoringMapperImpl) {
        this.dataMonitoringMapperImpl = dataMonitoringMapperImpl;
    }

    public String getWnDataCount() {
        Map<String, String> para = new HashMap<>();
        List<Map> res = new ArrayList<>();
        Map<String, Integer> el = new HashMap<>();
        String success = "true";
        String error = "查询成功";
        try {
            para.put("num", "60");
            Integer js = dataMonitoringMapperImpl.getWnDataSortCount(para) == null ? 0 : dataMonitoringMapperImpl.getWnDataSortCount(para);
            para.put("num", "80");
            Integer cs = dataMonitoringMapperImpl.getWnDataSortCount(para) == null ? 0 : dataMonitoringMapperImpl.getWnDataSortCount(para);
            para.put("num", "03");
            Integer fw = dataMonitoringMapperImpl.getWnDataSortCount(para) == null ? 0 : dataMonitoringMapperImpl.getWnDataSortCount(para);
            para.put("num", "70");
            Integer zh = dataMonitoringMapperImpl.getWnDataSortCount(para) == null ? 0 : dataMonitoringMapperImpl.getWnDataSortCount(para);
            int sum = js + cs + fw + zh;
            el.put("sum", sum);
            res.add(el);
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getWnDataSortCount() {
        Map<String, String> para = new HashMap<>();
        List<Map> res = new ArrayList<>();
        Map<String, Integer> el = new HashMap<>();
        String success = "true";
        String error = "查询成功";
        try {
            para.put("num", "60");
            Integer js = dataMonitoringMapperImpl.getWnDataSortCount(para) == null ? 0 : dataMonitoringMapperImpl.getWnDataSortCount(para);
            para.put("num", "80");
            Integer cs = dataMonitoringMapperImpl.getWnDataSortCount(para) == null ? 0 : dataMonitoringMapperImpl.getWnDataSortCount(para);
            para.put("num", "03");
            Integer fw = dataMonitoringMapperImpl.getWnDataSortCount(para) == null ? 0 : dataMonitoringMapperImpl.getWnDataSortCount(para);
            para.put("num", "70");
            Integer zh = dataMonitoringMapperImpl.getWnDataSortCount(para) == null ? 0 : dataMonitoringMapperImpl.getWnDataSortCount(para);
            el.put("js", js);
            el.put("cs", cs);
            el.put("fw", fw);
            el.put("zh", zh);
            res.add(el);
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getCatalogCount() {
        List<Map> res = new ArrayList<>();
        Map<String, Integer> el = new HashMap<>();
        String success = "true";
        String error = "查询成功";
        try {
            el.put("data", dataMonitoringMapperImpl.getSpaceCount() + dataMonitoringMapperImpl.getBusinessCount());
            res.add(el);
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getSpaceCount() {
        List<Map> res = new ArrayList<>();
        Map<String, Integer> el = new HashMap<>();
        String success = "true";
        String error = "查询成功";
        try {
            el.put("data", dataMonitoringMapperImpl.getSpaceCount());
            res.add(el);
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getBusinessCount() {
        List<Map> res = new ArrayList<>();
        Map<String, Integer> el = new HashMap<>();
        String success = "true";
        String error = "查询成功";
        try {
            el.put("data", dataMonitoringMapperImpl.getBusinessCount());
            res.add(el);
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getBusinessCount_wn() {
        List<Map> res = new ArrayList<>();
        Map<String, Integer> el = new HashMap<>();
        String success = "true";
        String error = "查询成功";
        try {
            el.put("data", dataMonitoringMapperImpl.getBusinessCount_wn());
            res.add(el);
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getBusinessCount_zf() {
        List<Map> res = new ArrayList<>();
        Map<String, Integer> el = new HashMap<>();
        String success = "true";
        String error = "查询成功";
        try {
            el.put("data", dataMonitoringMapperImpl.getBusinessCount_zf());
            res.add(el);
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getWnDataSum() {
        Map<String, String> para = new HashMap<>();
        List<Map> res = new ArrayList<>();
        Map<String, Integer> el = new HashMap<>();
        String success = "true";
        String error = "查询成功";
        try {
            para.put("num", "60");
            Integer js = dataMonitoringMapperImpl.getWnDataSum(para);
            para.put("num", "80");
            Integer cs = dataMonitoringMapperImpl.getWnDataSum(para);
            para.put("num", "03");
            Integer fw = dataMonitoringMapperImpl.getWnDataSum(para);
            para.put("num", "70");
            Integer zh = dataMonitoringMapperImpl.getWnDataSum(para);
            el.put("js", js);
            el.put("cs", cs);
            el.put("fw", fw);
            el.put("zh", zh);
            res.add(el);
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getQCSum() {
        List<Map> res = new ArrayList<>();
        Map<String, Integer> el = new HashMap<>();
        String success = "true";
        String error = "查询成功";
        try {
            el.put("data", dataMonitoringMapperImpl.getQCSum());
            res.add(el);
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getDataClearSum() {
        List<Map> res = new ArrayList<>();
        Map<String, Integer> el = new HashMap<>();
        String success = "true";
        String error = "查询成功";
        try {
            el.put("data", dataMonitoringMapperImpl.getDataClearSum());
            res.add(el);
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getConsumerSum() {
        List<Map> res = new ArrayList<>();
        Map<String, Integer> el = new HashMap<>();
        String success = "true";
        String error = "查询成功";
        try {
            el.put("DataResource", dataMonitoringMapperImpl.getDataResourceSum());
            el.put("Record", dataMonitoringMapperImpl.getRecordSum());
            el.put("BigData", dataMonitoringMapperImpl.getBigDataSum());
            el.put("Credit", dataMonitoringMapperImpl.getCreditSum());
            res.add(el);
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }
//
//    public String getDataResourceSum() {
//        List<Map> res = new ArrayList<>();
//        Map<String, Integer> el = new HashMap<>();
//        String success = "true";
//        String error = "查询成功";
//        try {
//            el.put("data", wnDataMapper.getDataResourceSum());
//            res.add(el);
//        } catch (Exception e) {
//            success = "false";
//            error = "查询失败！";
//            System.out.println(error);
//        }
//        return getMsg(res.size(), success, res, error);
//    }
//
//    public String getRecordSum() {
//        List<Map> res = new ArrayList<>();
//        Map<String, Integer> el = new HashMap<>();
//        String success = "true";
//        String error = "查询成功";
//        try {
//            el.put("data", wnDataMapper.getRecordSum());
//            res.add(el);
//        } catch (Exception e) {
//            success = "false";
//            error = "查询失败！";
//            System.out.println(error);
//        }
//        return getMsg(res.size(), success, res, error);
//    }
//
//    public String getBigDataSum() {
//        List<Map> res = new ArrayList<>();
//        Map<String, Integer> el = new HashMap<>();
//        String success = "true";
//        String error = "查询成功";
//        try {
//            el.put("data", wnDataMapper.getBigDataSum());
//            res.add(el);
//        } catch (Exception e) {
//            success = "false";
//            error = "查询失败！";
//            System.out.println(error);
//        }
//        return getMsg(res.size(), success, res, error);
//    }
//
//    public String getCreditSum() {
//        List<Map> res = new ArrayList<>();
//        Map<String, Integer> el = new HashMap<>();
//        String success = "true";
//        String error = "查询成功";
//        try {
//            el.put("data", wnDataMapper.getCreditSum());
//            res.add(el);
//        } catch (Exception e) {
//            success = "false";
//            error = "查询失败！";
//            System.out.println(error);
//        }
//        return getMsg(res.size(), success, res, error);
//    }

    public String getGovernSituation() {
        Map<String, String> para = new HashMap<>();
        List<Map> res = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String success = "true";
        String error = "查询成功";
        try {
            cal.add(Calendar.MONTH, -13);
            for (int i = 0; i < 12; ++i) {
                cal.add(Calendar.MONTH, +1);
                para.put("date", sdf.format(cal.getTime()));
                Map<String, Object> el = new HashMap<>();
                el.put("date", sdf.format(cal.getTime()));
                el.put("sum", dataMonitoringMapperImpl.getGovernSituation(para) == null ? 0 : dataMonitoringMapperImpl.getGovernSituation(para));
                res.add(el);
            }
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getClearSituation() {
        Map<String, String> para = new HashMap<>();
        List<Map> res = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String success = "true";
        String error = "查询成功";
        try {
            cal.add(Calendar.MONTH, -13);
            for (int i = 0; i < 12; ++i) {
                cal.add(Calendar.MONTH, +1);
                para.put("date", sdf.format(cal.getTime()));
                Map<String, Object> el = new HashMap<>();
                el.put("date", sdf.format(cal.getTime()));
                el.put("sum", dataMonitoringMapperImpl.getClearSituation(para) == null ? 0 : dataMonitoringMapperImpl.getClearSituation(para));
                res.add(el);
            }
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getDataShard_business() {
        List<Map> res = new ArrayList<>();
        String success = "true";
        String error = "查询成功";
        try {
            res = dataMonitoringMapperImpl.getDataShard_business();
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getDataShard_space() {
        List<Map> res = new ArrayList<>();
        String success = "true";
        String error = "查询成功";
        try {
            res = dataMonitoringMapperImpl.getDataShard_space();
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getShareSituation_business() {
        List<Map> res = new ArrayList<>();
        String success = "true";
        String error = "查询成功";
        try {
            List<Map> re = dataMonitoringMapperImpl.getShareSituation_business();
            for (Map r : re) {
                Map<String, Object> el = new HashMap<>();
                el.put("date", r.get("MONTH"));
                el.put("count", r.get("COUNT"));
                res.add(el);
            }
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getShareSituation_space() {
        List<Map> res = new ArrayList<>();
        String success = "true";
        String error = "查询成功";
        try {
            List<Map> re = dataMonitoringMapperImpl.getShareSituation_space();
            for (Map r : re) {
                Map<String, Object> el = new HashMap<>();
                el.put("date", r.get("MONTH"));
                el.put("count", r.get("COUNT"));
                res.add(el);
            }
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getCellSituation_space() {
        List<Map> res = new ArrayList<>();
        Map<String, Integer> el = new HashMap<>();
        String success = "true";
        String error = "查询成功";
        try {
            el.put("data", dataMonitoringMapperImpl.getCellSituation_space());
            res.add(el);
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getCellSituation_business() {
        List<Map> res = new ArrayList<>();
        Map<String, Integer> el = new HashMap<>();
        String success = "true";
        String error = "查询成功";
        try {
            List<Map> t = dataMonitoringMapperImpl.getCellSituation_business();
            int sum = 0;
            for (Map m : t) {
                el.put(String.valueOf(m.get("SORT")), Integer.parseInt(m.get("COUNT").toString()));
                sum += Integer.parseInt(m.get("COUNT").toString());
            }
            el.put("sum", sum);
            res.add(el);
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getCollectsTrend() {
        List<Map> res = new ArrayList<>();
        String success = "true";
        String error = "查询成功";
        try {
            List<Map> re = dataMonitoringMapperImpl.getCollectsTrend();
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            cal.add(Calendar.MONTH, -13);
            for (int i = 0; i < 12; ++i) {
                boolean flag = true;
                cal.add(Calendar.MONTH, +1);
                Map<String, Object> el = new HashMap<>();
                for (Map r : re) {
                    if (r.get("MONTH").equals(sdf.format(cal.getTime()))) {
                        el.put("date", r.get("MONTH"));
                        el.put("sum", r.get("SUM"));
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    el.put("date", sdf.format(cal.getTime()));
                    el.put("sum", 0);
                }
                res.add(el);
            }
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getChannelStatusMain(net.sf.json.JSONObject o) {
        List<Map> res = new ArrayList<>();
        Map<String, String> m = new HashMap<>();
        PageInfo<Map> info = null;
        String success = "true";
        String error = "查询成功";
        int page = Integer.parseInt(o.getString("pageIndex"));
        int pageSize = Integer.parseInt(o.getString("pageSize"));
        try {
            m.put("name", o.get("dataSource_name").toString());
            m.put("type", o.get("DataSource_type").toString());
            m.put("status", o.get("dataSource_status").toString());
            PageHelper.startPage(page, pageSize);
            res = dataMonitoringMapperImpl.getChannelStatusMain(m);
            info = new PageInfo<>(res);
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg((int) info.getTotal(), success, res, error, pageSize);
    }

    public String getChannelStatusDetail(net.sf.json.JSONObject o) {
        List<Map> res = new ArrayList<>();
        Map<String, String> m = new HashMap<>();
        PageInfo<Map> info = null;
        String success = "true";
        String error = "查询成功";
        int page = Integer.parseInt(o.getString("pageIndex"));
        int pageSize = Integer.parseInt(o.getString("pageSize"));
        try {
            m.put("id", o.getString("DataSource_Id"));
            PageHelper.startPage(page, pageSize);
            res = dataMonitoringMapperImpl.getChannelStatusDetail(m);
            info = new PageInfo<>(res);
        } catch (Exception e) {
            success = "false";
            error = "查询失败！";
            System.out.println(error);
        }
        return getMsg((int) info.getTotal(), success, res, error, pageSize);
    }

    @Transactional
    public String insertChannelStatus(net.sf.json.JSONObject o) {
        List<Map> res = new ArrayList<>();
        Map<String, String> el = new HashMap<>();
        String success = "true";
        String error = "成功";
        List<Integer> status = new ArrayList<>();
        try {
            String id = o.getString("id");
            Map<String, String> m1 = new HashMap<>();
            m1.put("id",o.getString("id"));
            m1.put("name", o.getString("name"));
            m1.put("ip", o.getString("ip"));
            m1.put("type", o.getString("type"));
            if (Objects.equals(id, "")) {
                //id为空则是新增，插入然后获取新生成的uuid，Detail表中不存在相应记录所以不删除
                status.add(dataMonitoringMapperImpl.insertChannelStatusMain(m1));
                id = dataMonitoringMapperImpl.getMainIdByIp(o.getString("ip"));
            } else {
                //id不为空则是更新，然后删除Detail表中的相应记录
                status.add(dataMonitoringMapperImpl.updateChannelStatusMain(m1));
                Map<String, String> m2 = new HashMap<>();
                m2.put("id", id);
                dataMonitoringMapperImpl.deleteChannelStatusDetail(m2);
            }
            JSONArray arr = o.getJSONArray("detailList");
            if (arr.size() != 0) {
                for (int i = 0; i < arr.size(); ++i) {
                    Map<String, String> m = new HashMap<>();
                    m.put("id", id);
                    m.put("unitId", arr.getJSONObject(i).getString("DATASOURCE_UNIT_ID"));
                    m.put("unitType", arr.getJSONObject(i).getString("DATASOURCE_UNIT_TYPE"));
                    m.put("unitCode", arr.getJSONObject(i).getString("DATASOURCE_UNIT_CODE"));
                    m.put("unitPort", arr.getJSONObject(i).getString("DATASOURCE_UNIT_PORT"));
                    m.put("unitInstance", arr.getJSONObject(i).getString("DATASOURCE_UNIT_INSTANCE"));
                    m.put("unitUser", arr.getJSONObject(i).getString("DATASOURCE_UNIT_USER"));
                    m.put("unitPassword", arr.getJSONObject(i).getString("DATASOURCE_UNIT_PASSWORD"));
                    m.put("unitStatus", "1");
                    status.add(dataMonitoringMapperImpl.insertChannelStatusDetail(m));
                }
            }
            el.put("status", "success");
            for (Integer integer : status) {
                if (integer == 0) {
                    //有未成功的插入则全体回滚
                    el.put("status", "error");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    break;
                }
            }
            res.add(el);
        } catch (Exception e) {
            success = "false";
            error = "失败！";
            el.put("status", "error");
            res.add(el);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            System.out.println(e);
        }
        return getMsg(res.size(), success, res, error);
    }

    @Transactional
    public String deleteChannelStatus(net.sf.json.JSONObject o){
        List<Map> res = new ArrayList<>();
        Map<String, String> el = new HashMap<>();
        Map<String, String> m = new HashMap<>();
        String success = "true";
        String error = "成功";
        try{
            m.put("id",o.getString("id"));
            dataMonitoringMapperImpl.deleteChannelStatusMain(m);
            dataMonitoringMapperImpl.deleteChannelStatusDetail(m);
            el.put("status", "success");
            res.add(el);
        }catch (Exception e) {
            success = "false";
            error = "失败！";
            el.put("status", "error");
            res.add(el);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            System.out.println(e);
        }
        return getMsg(res.size(), success, res, error);
    }

    public String getDataServiceStatesMonitoring(net.sf.json.JSONObject o){
        List<Map> res = new ArrayList<>();
        Map<String, String> m = new HashMap<>();
        PageInfo<Map> info = null;
        String success = "true";
        String error = "查询成功";
        int page = Integer.parseInt(o.getString("pageIndex"));
        int pageSize = Integer.parseInt(o.getString("pageSize"));
        try{
            m.put("name", o.getString("name"));
            m.put("startTime", o.getString("startTime"));
            m.put("endTime", o.getString("endTime"));
            m.put("unitId", o.getString("unitId"));
            PageHelper.startPage(page, pageSize);
            res = dataMonitoringMapperImpl.getDataServiceStatesMonitoring(m);
            info = new PageInfo<>(res);
        }catch (Exception e) {
            success = "false";
            error = "失败！";
            System.out.println(e);
        }
        return getMsg((int) info.getTotal(), success, res, error, pageSize);
    }

    public String getDataServiceStatesMonitoring_Detail(net.sf.json.JSONObject o){
        List<Map> res = new ArrayList<>();
        Map<String, String> m = new HashMap<>();
        PageInfo<Map> info = null;
        String success = "true";
        String error = "查询成功";
        int page = Integer.parseInt(o.getString("pageIndex"));
        int pageSize = Integer.parseInt(o.getString("pageSize"));
        try{
            m.put("cid", o.getString("cid"));
            m.put("state", o.getString("state"));
            m.put("startTime", o.getString("startTime"));
            m.put("endTime", o.getString("endTime"));
            PageHelper.startPage(page, pageSize);
            res = dataMonitoringMapperImpl.getDataServiceStatesMonitoring_Detail(m);
            info = new PageInfo<>(res);
        }catch (Exception e) {
            success = "false";
            error = "失败！";
            System.out.println(e);
        }
        return getMsg((int) info.getTotal(), success, res, error, pageSize);
    }

    private String getMsg(int size, String success, List<Map> res, String error, int pageSize) {
        ResultSelectMsg resultSelectMsg = new ResultSelectMsg();
        resultSelectMsg.setTotalRowCount(size);
        resultSelectMsg.setSuccess(success);
        resultSelectMsg.setRows(res);
        resultSelectMsg.setError(error);
        resultSelectMsg.setPageSize(pageSize);
        JSONObject result = new JSONObject(resultSelectMsg.getMsg());
        return result.toString();
    }

    private String getMsg(int size, String success, List<Map> res, String error) {
        ResultSelectMsg resultSelectMsg = new ResultSelectMsg();
        resultSelectMsg.setTotalRowCount(size);
        resultSelectMsg.setSuccess(success);
        resultSelectMsg.setRows(res);
        resultSelectMsg.setError(error);
        resultSelectMsg.setPageSize(1);
        resultSelectMsg.setPageCount(1);
        JSONObject result = new JSONObject(resultSelectMsg.getMsg());
        return result.toString();
    }
}
